import { useState, useRef, useEffect } from 'react'
import { Button, MessagePlugin } from 'tdesign-react'
import KeepAlive from 'react-activation'
import { useTranslation } from 'react-i18next'
import { ApiRequest, apis } from '@/service'
import CreateQuestionnaireQuestions from './CreateQuestionnaireQuestions'
import CreateQuesionnaireTitle from './CreateQuestionnaireTitle'
import '../index.less'

const {
  practiceService: {
    insertQuestionnaire
  }
} = apis

const CreateQuestionnaires = () => {
  const { t } = useTranslation(['webGames'])

  const [title, setTitle] = useState('')
  const [questionList, setQuestionList] = useState<QuestionType[]>([])
  // 设置题目的下标
  const [questionFlag, setQuestionFlag] = useState(-1)

  const createQuestionsRef = useRef(null)

  const _initQuestion: QuestionType = {
    title: '',
    type: '',
    optionList: [],
  }

  //添加下一个题目/下一步
  const addNextQuestion = () => {
    let _questionFlag = questionFlag + 1
    setQuestionFlag(_questionFlag)
    if (!questionList[_questionFlag]) {
      // 如果游标所在的位置不存在数据，就添加一个问题（每个问题必须填完之后才能填写下个问题）
      let _questionList = [...questionList]
      _questionList.push(_initQuestion)
      setQuestionList(_questionList)
    } else {
      // 如果游标所指位置已经存在数据了
    }
  }

  const onQuestionPrevButtonClick = () => {
    setQuestionFlag(questionFlag - 1)
  }

  const isFullQuestion = (question: QuestionType) => {
    if (!question.title || !question.type) {
      return false
    }
    if (question.type == 'radio' && question.optionList?.length == 0) {
      return false
    }
    return true
  }

  const submitQuestionnaire = () => {
    const params: QuestionnaireType = {
      title: '', // title未处理
      questionList: questionList,
      submitNumber: 0
    }
    ApiRequest({ api: insertQuestionnaire, params }).then((res: any) => {
      const { code = -1, data = [], note = '' } = res
      if (code > 0) {
        MessagePlugin.success({
          content: note,
          placement: 'top-right',
          duration: 2000
        })
      }
    })
  }

  useEffect(() => {
    if (questionFlag >= 0 && createQuestionsRef?.current) {
      console.log((createQuestionsRef?.current as any).questionTypeList)
      console.log((createQuestionsRef?.current as any).getQuestionData())
    }
  }, [questionFlag])



  return <div className='create-questionnaires frame' >
    {questionFlag == -1 ? <div className='stage1'>
      <CreateQuesionnaireTitle setTitle={setTitle} title={title} />
      <Button className='add-next-question' onClick={() => { addNextQuestion() }} >下一步</Button>
    </div> : <div className='stage2'>
      <CreateQuestionnaireQuestions
        ref={createQuestionsRef}
        questionFlag={questionFlag}
        // getQuestionData={getQuestionData}
        questionList={questionList}
        setQuestionFlag={setQuestionFlag}
        setQuestionList={setQuestionList}
      />
      <Button
        className='back-button'
        onClick={onQuestionPrevButtonClick}
      >上一步</Button>

      {isFullQuestion(questionList[questionFlag]) && <Button
        className='next-button'
        onClick={() => { addNextQuestion() }}
      >下一步</Button>}
      <Button
        className='submit-questionnaire'
        onClick={submitQuestionnaire}
      >完成</Button>
    </div>}
  </div>
}

const KeepAliveComponent = (props: any) => {
  return <KeepAlive key='questionaires-create-questionaires' name='questionaires-create-questionaires'>
    <CreateQuestionnaires {...props} />
  </KeepAlive>
}

export default KeepAliveComponent
